<template>
  <div class="map-container">
    <div ref="mapContainer" class="map"></div>
    <div v-if="selectedLocation" class="legend">
      <p>选中的位置经纬度：</p>
      <p>{{ selectedLocation.lng }}, {{ selectedLocation.lat }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineProps } from "vue"
import AMapLoader from "@amap/amap-jsapi-loader"

const emits = defineEmits(["selectedLocation"])

const mapContainer = ref()

let map = null
const selectedLocation = ref(null)

onMounted(() => {
  AMapLoader.load({
    key: "9a1c1cbcf62c29381e7d9da3b8852b17", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map = new AMap.Map(mapContainer.value, {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: [113.261546, 23.127893] // 初始化地图中心点位置
      })

      addClickEvent()
    })
    .catch((e) => {
      console.log(e)
    })
})

onUnmounted(() => {
  map?.destroy()
})

const addClickEvent = () => {
  map.on("click", (e) => {
    selectedLocation.value = {
      lng: e.lnglat.lng,
      lat: e.lnglat.lat
    }
    emits("selectedLocation", selectedLocation.value)
  })
}

defineExpose({
  selectedLocation
})
</script>

<style scoped>
.map-container {
  position: relative;
  height: 400px;
}
.map {
  height: 100%;
}
.legend {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: #fff;
  padding: 10px;
  border: 1px solid #ccc;
}
</style>
